package com.jt.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;


@RestController
public class ConsumerController {
    @Value("${server.port}")
    private String server;
    /**
     * 从spring容器中获取restTemplate对象，实现对远端服务的调用
     * spring本身没有对该类没有配置 所以要到启动类中您行配置
     */
    @Autowired
    private RestTemplate restTemplate;//底层是模板方法设计模式
    @Autowired
    private LoadBalancerClient loadBalancerClient;//发现与获取远端服务实例
    @Autowired
    private RestTemplate loadBalancedRestTemplate;
    /**
     * 实现对远端服务sca-provider的调用
     * @return
     */
    @GetMapping("/consumer/doEcho1")
    public String doRestEcho1(){
       //定义远端服务的url
        String url = "http://localhost:8081/provider/echo/8082";
        //基于restTemplate对象进行服务调用
        return restTemplate.getForObject(url, String.class);
    }
    @GetMapping("/consumer/doEcho2")
    public String doRestEcho2(){
        //获取远端服务信息
        ServiceInstance serviceInstance = loadBalancerClient.choose("sca-provider");
        //定义远端服务的url 动态获取  在这里格式化一下 %s依次对应后面的可变参数进行自动拼接
        String url = String.format("http://%s:%s/provider/echo/%s",serviceInstance.getHost(),serviceInstance.getPort(),server);
        System.out.println("请求url"+url);
        return restTemplate.getForObject(url, String.class );
    }
    @GetMapping("/consumer/doEcho3")
    public String doRestEcho3(){
        String serviceId = "sca-provider";
        //String url = "http://sca-provider/provider/echo/%s" + server;
        String url = String.format("http://%s/provider/echo/%s",serviceId,server);
        //在底层拦截器中获取远端服务实例，实现负载均衡 简化版
        //使用@LoadBalanced注解声明
        return loadBalancedRestTemplate.getForObject(url, String.class );
    }
}
